const { tokenResolver } = require('../utils/token')
const { TOKEN_INVALID } = require('../error/errorType')

const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header
  if (!authorization) {
    return ctx.app.emit('error', new Error(TOKEN_INVALID), ctx)
  }
  let token = authorization.replace('Bearer ', "")

  //解析token
  let userInfo = null;
  try {
    userInfo = tokenResolver(token)
  } catch (error) {
    return ctx.app.emit('error', new Error(TOKEN_INVALID), ctx)
  }
  ctx.userInfo = userInfo
  await next()
}

module.exports = auth